import { Component, Inject } from '@angular/core';
import { Router } from '@angular/router';
import {Md5} from "ts-md5/dist/md5";
import * as Global from '../../globals/global';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-login-component',
  templateUrl: './login.component.html'
})
export class LoginComponent {
  public isShow = false;
  public warnMsg: string;
  public loginId: string;
  public password: string;
 
  httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json; charset=utf-8'})
    ,withCredentials: true
  };

  constructor(private router: Router, private http: HttpClient) {
  } 

  public checkLogin() {
    if (!this.loginId) {
      this.isShow = true;
      this.warnMsg = "Please input Login ID";
      return;
    }
    if (!this.password) {
      this.isShow = true;
      this.warnMsg = "Please input password";
      return;
    }
    this.isShow = false;
    this.warnMsg = "password";

    this.http.post<LoginModel>(Global.api.checkLogin, {
      loginID : this.loginId,
      password : Md5.hashStr(this.password).toString()
    }
    
    , this.httpOptions).subscribe(result => {
      console.log(result);
      switch(result.loginResult) {
        case 1: this.router.navigateByUrl('/'); break;
        case 2: this.warnMsg = "User not found"; this.isShow = true; break;
        case 3: this.warnMsg = "Wrong password"; this.isShow = true; break;
      } 
    }, error => console.error(error));
  }
}

interface LoginModel {
  loginID: string;
  loginResult: number;
  defaultQueryCityCode: string
}
